//
//  PurchaseViewController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 15/11/16.
//  Copyright © 2015年 sgone. All rights reserved.
//

#import "PurchaseViewController.h"
#import "LoginViewController.h"
#import "FDInquiryView.h"
#import "MBProgressHUD.h"
#import "MBProgressHUD+MJ.h"
#import "Toast+UIView.h"
#import "AFNetworking.h"
#import "HPReleaseTextViewController.h"

@interface PurchaseViewController ()<UIScrollViewDelegate,inquiryViewConfirmClickDelegate,UIAlertViewDelegate>


{

  
    UISegmentedControl * segmentedControl;
     NSDictionary *goodsMessageDic;
}


@property(nonatomic,strong) SourceViewController *source2;
@property(nonatomic,strong) FruitLoopsController *fruits;
@property(nonatomic,strong) UIScrollView *myscroll;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) FDInquiryView *inquiryView;




@end

@implementation PurchaseViewController



//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}





- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToSubControllerClick:) name:@"pushToSubControllerClick" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inquiryClick:) name:@"topInquiryClick" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideRightButton:) name:@"hideRightButton" object:nil];
    
    [self creatUI];
    
    
    
    

}











- (void)inquiryClick:(id)sender {
    
    NSNotification *user = (NSNotification *)sender;
    NSDictionary *dic = (NSDictionary *)user.userInfo;
    
    goodsMessageDic = [NSDictionary dictionaryWithDictionary:dic];
    
     self.inquiryView = [[FDInquiryView alloc] initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight)];
     self.inquiryView.delegate = self;
    [ self.inquiryView setCustomAlertViewWithTitle:dic[@"shop_name"] message:dic[@"username"] unit:dic[@"least_unit"] cancel:@"取消" verify:@"确定"];
    [self.tabBarController.view addSubview: self.inquiryView];
    
}





- (void)inquiryViewConfirmClick:(NSDictionary *)dic {
    
    [self setInquiryMessageByPid:goodsMessageDic[@"id"] nums:dic[@"num"] chart_text:dic[@"message"]];
}

- (void)setInquiryMessageByPid:(NSString *)pid nums:(NSString *)nums chart_text:(NSString *)chart_text {
    
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@add_chart_log",SERVER_ADDRESS3];
    NSDictionary *parms = @{@"uid" :  [self.dataHandler.userDic objectForKey:@"wId"] ,@"user_type" : @"3" , @"pid" : pid, @"nums" : nums , @"chart_text" : chart_text,@"chart_type"  : @"2"};
    
    if (nums.length == 0) {
        
        [self.inquiryView makeToast:@"需求量不能为空"];
        return;
    }
    else if (chart_text.length == 0)
    {
    
    
        [self.inquiryView makeToast:@"备注不能为空"];
        return;
    
    
    }
    
        [self.inquiryView removeFromSuperview];
    
    [MBProgressHUD showHUDAddedTo:self.myscroll animated:YES];
    
    [self.manager POST:urlStr parameters:parms success:^(NSURLSessionDataTask *task, id responseObject) {
   

        
        if ([responseObject[@"erorr_flag"] intValue] == 0) {
            
            
            
            [MBProgressHUD hideAllHUDsForView:self.myscroll animated:YES];
            [self.view makeToast:@"发送成功"];

            
            
        }
        else
        {
            
            [MBProgressHUD hideAllHUDsForView:self.myscroll animated:YES];
            NSString *str = responseObject[@"result_msg"];
            [self.view makeToast:str];
        
        }
       
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.myscroll animated:YES];
        [self.view makeToast:@"请检查网络"];

        
    }];
    
    
    
    
/*
    HPHttpService *inquiryService = [[HPHttpService alloc] init];
    
    [MBProgressHUD showHUDAddedTo:self.myscroll animated:YES];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [inquiryService setInquiryMessageByPid:pid nums:nums chart_text:chart_text success:^(NSString *resultStr) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if ([resultStr isEqualToString:@"success"]) {
                    
                    [MBProgressHUD hideAllHUDsForView:self.myscroll animated:YES];
                    
                    [MBProgressHUD showSuccess:@"发送成功"];
                }
            });
        } error:^(NSString *errorInfo) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideAllHUDsForView:self.myscroll animated:YES];
                [OtherLogin otherUserLoginTheSameUsername:errorInfo navigationController:self.navigationController];
            });
        }];
    });
 
 */
}


-(void)rightButClick2:(id)sender
{
    PhotoController *photo = [[PhotoController alloc]initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:photo animated:YES];
}


- (void)releaseTextClick:(UILongPressGestureRecognizer *)gesture {
    
    if(gesture.state == UIGestureRecognizerStateBegan) {
        
        HPReleaseTextViewController *commentVC = [[HPReleaseTextViewController alloc] initWithNibName:nil bundle:nil];
        
        [self.navigationController pushViewController:commentVC animated:YES];
    }
    
    //    [self presentViewController:commentVC animated:YES completion:nil];
}



-(void)creatUI
{
    
    
//    
//    recurringActive = [[UIImage imageNamed:@"fs_common_search_normal"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    ios7 要使用   imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal

 
    
    
    
    segmentedControl = [[UISegmentedControl alloc]initWithFrame:CGRectMake((ViewWidth - 140)/2, 28, 120 /FDLaOt, 30)];
    [segmentedControl insertSegmentWithTitle:@"货源" atIndex:0 animated:YES];
    segmentedControl.backgroundColor = BenSe_COLOR;
    segmentedControl.tintColor = [UIColor whiteColor];
    segmentedControl.layer.masksToBounds = YES;
    segmentedControl.layer.cornerRadius = 3.0f;
    
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:15/FDLaOt],NSFontAttributeName ,nil];
//    [UIFont fontWithName:@"AppleGothic"size:17]
    [segmentedControl setTitleTextAttributes:dic forState:UIControlStateNormal];
  
    [segmentedControl insertSegmentWithTitle:@"水果圈" atIndex:1 animated:YES];
    [segmentedControl addTarget:self action:@selector(controlPressed:) forControlEvents:UIControlEventValueChanged];
    [self.topView addSubview:segmentedControl];
    
    //选中的位置选择
    segmentedControl.selectedSegmentIndex = 0;

    
//    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    
    self.myscroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, ViewWidth, ViewHeight - 64 - 48)];
    self.myscroll.contentSize = CGSizeMake(ViewWidth *2, ViewHeight - 64- 48);
    self.myscroll.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.myscroll];
    self.myscroll.scrollEnabled = NO;
    self.myscroll.bounces = NO;
    self.myscroll.delegate = self;
    self.myscroll.pagingEnabled = YES;
    self.myscroll.showsHorizontalScrollIndicator = NO;
    self.myscroll.directionalLockEnabled = YES;
    
    self.topView.hidden = NO;
    self.rightBut.frame = CGRectMake(ViewWidth * 0.8, 20, 64, 44) ;
    [self.rightBut setImage:[UIImage imageNamed:@"btnImage2"] forState:UIControlStateNormal];
    self.rightBut.hidden = YES;
    
    
    
    
    
    
    //        self.rightBut.imageEdgeInsets = UIEdgeInsetsZero;
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(releaseTextClick:)];
    longPress.minimumPressDuration = 0.8;
    [self.rightBut addGestureRecognizer:longPress];
    
    
    [self.rightBut addTarget:self action:@selector(rightButClick2:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.view addSubview:self.rightBut];
    
    
    
    
    self.source2  = [[SourceViewController alloc]initWithNibName:nil bundle:nil];
    self.source2.view.frame = CGRectMake(0, 0, ViewWidth, ViewHeight);
    
    [self addChildViewController:self.source2];
    [self.myscroll addSubview:self.source2.view];
    
    
    
    self.fruits = [[FruitLoopsController alloc]initWithNibName:nil bundle:nil];
    self.fruits.view.frame = CGRectMake(ViewWidth, 0, ViewWidth, ViewHeight);
    [self addChildViewController:self.fruits];
    [self.myscroll addSubview:self.fruits.view];
        
}



- (void) controlPressed:(id)sender
{
    int selectedIndex =  segmentedControl.selectedSegmentIndex;
    /* 添加代码,处理值的变化 */
    NSLog(@"Segment %d selected\n", selectedIndex);
    
    
    
    
    if (selectedIndex == 0)
    {
        [self.myscroll setContentOffset:CGPointMake(0, 0) animated:YES];
        self.rightBut.hidden = YES;
    }
    else if (selectedIndex == 1)
    {
        [self.myscroll setContentOffset:CGPointMake([[UIScreen mainScreen] bounds].size.width, 0) animated:YES];
        self.rightBut.hidden = NO;
        
        

    }
}

- (void)pushToSubControllerClick:(id)sender {
    
    
    NSNotification *user = (NSNotification *)sender;
    NSDictionary *dic = (NSDictionary *)user.userInfo;
    
    UIViewController *viewController = dic[@"controller"];
    
    [self.navigationController pushViewController:viewController animated:YES];
}



-(void)dealloc
{

    [[NSNotificationCenter defaultCenter] removeObserver:self];


}


- (void)hideRightButton:(id)sender {
    
    NSNotification *user = (NSNotification *)sender;
    NSDictionary *dic = (NSDictionary *)user.userInfo;
    
    if ([dic[@"state"] intValue] == 0) {
        
        self.rightBut.hidden = YES;
    } else {
        
        self.rightBut.hidden = NO;
    }
}
@end
